package com.hsck.order.kds.main

import android.view.LayoutInflater
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import com.hsck.order.kds.R
import com.hsck.order.kds.base.Constants
import com.hsck.order.kds.base.common.jump
import com.hsck.order.kds.base.common.setOnSingleClickListener
import com.hsck.order.kds.base.isnoam.view.BaseActivity
import com.hsck.order.kds.databinding.ActivityMainBinding
import com.hsck.order.kds.main.dialog.PersonalDl
import com.hsck.order.kds.main.dialog.PrinterDl
import com.hsck.order.kds.main.fragment.bake.GrilledVegetablesFragment
import com.hsck.order.kds.main.fragment.noodles.NoodlesAnVegetablesFragment
import com.hsck.order.kds.main.fragment.order.OrderDynamicsFragment
import com.hsck.order.kds.main.fragment.record.FoodDeliveryRecordFragment
import com.hsck.order.kds.main.fragment.return_deishe.ReturnOfDishesFragment
import com.hsck.order.kds.main.fragment.standard.StandardDishFragment
import com.hsck.order.kds.main.itf.UpdatableFragmentListener
import com.hsck.order.kds.setup.ClearingSettingsActivity
import com.hsck.order.kds.setup.KitchenDisplaySettingsActivity
import com.hsck.order.kds.setup.SetupActivity
import kotlinx.android.synthetic.main.activity_main.lin_main_dl
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class MainActivity : BaseActivity<ActivityMainBinding>() {
    override fun inflateBinding(inflater: LayoutInflater): ActivityMainBinding {
        return ActivityMainBinding.inflate(inflater)
    }

    private var currentFragment: Fragment? = null
    private var standardDishFragment = StandardDishFragment()
    private var grilledVegetablesFragment = GrilledVegetablesFragment()
    private var noodlesAnVegetablesFragment = NoodlesAnVegetablesFragment()
    private var orderDynamicsFragment = OrderDynamicsFragment()
    private var returnOfDishesFragment = ReturnOfDishesFragment()
    private var foodDeliveryRecordFragment = FoodDeliveryRecordFragment()
    private val coroutineScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    private var job: Job? = null

    //根据后台数据动态判断创建哪个fragment
    override fun initData() {
        super.initData()
        binding.apply {
            tableType = 0
            menuIndex = 0
            replaceFragment(standardDishFragment)
        }
    }

    override fun onResume() {
        super.onResume()
        fetchServerTimeAndStartClock()
    }

    override fun initListener() {
        super.initListener()
        binding.apply {
            dlMain.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
            //设置
            ivSetting.setOnClickListener {
                jump(SetupActivity::class.java)
            }
            //个人中心
            tvUserName.setOnClickListener {
                dlMain.openDrawer(GravityCompat.END)
                PersonalDl.show(this@MainActivity, lin_main_dl, dlMain)
            }
            //打印机
            ivPrint.setOnClickListener {
                dlMain.openDrawer(GravityCompat.END)
                PrinterDl.show(this@MainActivity, lin_main_dl, dlMain)
            }
            tvAll.setOnClickListener {
                changeTopTable(0)
            }
            tvTs.setOnClickListener {
                changeTopTable(1)
            }
            tvWm.setOnClickListener {
                changeTopTable(2)
            }
            tvDb.setOnClickListener {
                changeTopTable(3)
            }

            //标准划菜
            llStandard.setOnClickListener {
                replaceFragment(standardDishFragment)
            }
            //串烤划菜
            llBake.setOnClickListener {
                replaceFragment(grilledVegetablesFragment)
            }
            //粉面划菜
            llNoodles.setOnClickListener {
                replaceFragment(noodlesAnVegetablesFragment)
            }
            //订单动态
            llOrder.setOnClickListener {
                replaceFragment(orderDynamicsFragment)
            }
            //退菜动态
            llReturn.setOnClickListener {
                replaceFragment(returnOfDishesFragment)
            }
            //传菜记录
            llRecord.setOnClickListener {
                replaceFragment(foodDeliveryRecordFragment)
            }
            //厨显设置
            tvSetting.setOnClickListener {
                jump(KitchenDisplaySettingsActivity::class.java)
            }
            //沽清设置
            tvSellOut.setOnClickListener {
                jump(ClearingSettingsActivity::class.java)
            }
            // 上一页
            tvPreviousPagev.setOnSingleClickListener {
                (currentFragment as? OrderDynamicsFragment)?.onPageChange(false)
            }
            // 下一页
            tvNextPage.setOnSingleClickListener {
                (currentFragment as? OrderDynamicsFragment)?.onPageChange(true)
            }
        }
    }

    private fun changeTopTable(table: Int) {
        //顶部分类
        binding.tableType = table
        //当前Fragment中请求分类数据
    }

    private fun switchFragment(fragment: Fragment) {
        if (currentFragment != fragment) {
            val transaction = supportFragmentManager.beginTransaction()
            (currentFragment as? UpdatableFragmentListener)?.onFragmentInvisible()
            if (!fragment.isAdded) {
                transaction.add(R.id.frameLayout, fragment)
            }
            currentFragment?.let { transaction.hide(it) }
            transaction.show(fragment).commitAllowingStateLoss()
            currentFragment = fragment
            updateMenuIndex()
            (fragment as? UpdatableFragmentListener)?.onFragmentVisible()
        }
        when (fragment) {
            foodDeliveryRecordFragment -> {
                changeTopTable(-1)
            }
            returnOfDishesFragment -> {
                changeTopTable(-2)
            }
            else -> {
                changeTopTable(0)
            }
        }
    }


    private fun replaceFragment(fragment: Fragment) {
        val beginTransaction = supportFragmentManager.beginTransaction()
        if (currentFragment != null) {
            beginTransaction.remove(currentFragment!!)
        }
        beginTransaction.replace(R.id.frameLayout, fragment).commitAllowingStateLoss()
        currentFragment = fragment
        updateMenuIndex()
        (fragment as? UpdatableFragmentListener)?.onFragmentVisible()
        when (fragment) {
            foodDeliveryRecordFragment -> {
                changeTopTable(-1)
            }
            returnOfDishesFragment -> {
                changeTopTable(-2)
            }
            else -> {
                changeTopTable(0)
            }
        }
    }

    private fun updateMenuIndex() {
        binding.menuIndex = when (currentFragment) {
            is StandardDishFragment -> 0
            is GrilledVegetablesFragment -> 1
            is NoodlesAnVegetablesFragment -> 2
            is OrderDynamicsFragment -> 3
            is ReturnOfDishesFragment -> 4
            is FoodDeliveryRecordFragment -> 5
            else -> -1
        }
    }

    /**
     * 获取服务器时间，并启动时钟
     */
    private fun fetchServerTimeAndStartClock() {
        job?.cancel()
        val client = OkHttpClient()
        coroutineScope.launch(Dispatchers.IO) {
            try {
                val request = Request.Builder().url(Constants.BAI_DU).build()
                val response = client.newCall(request).execute()
                val dateHeader = response.header("Date") // 获取Date头
                val serverTimeMillis = parseServerTime(dateHeader)
                withContext(Dispatchers.Main) {
                    startClock(serverTimeMillis)
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    startClock(System.currentTimeMillis())
                }
                e.printStackTrace()
            }
        }
    }

    /**
     * 解析服务器时间
     */
    private fun parseServerTime(dateHeader: String?): Long {
        return try {
            val sdf = SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.CANADA)
            sdf.parse(dateHeader)?.time ?: System.currentTimeMillis()
        } catch (e: Exception) {
            System.currentTimeMillis() // 如果解析失败，返回当前本地时间
        }
    }

    /**
     * 启动时钟
     */
    private fun startClock(initialTimeMillis: Long) {
        var currentTimeMillis = initialTimeMillis
        job = coroutineScope.launch {
            while (isActive) {
                // 格式化时间
                val timeString = SimpleDateFormat(
                    "HH:mm:ss",
                    Locale.getDefault()
                ).format(Date(currentTimeMillis))
                binding.tvTime.text = timeString
                // 更新时间，每秒增加1000毫秒
                currentTimeMillis += 1000
                delay(1000)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        job?.cancel()
    }

    /**
     *
     * 参数：
     *     参数1：visible：true->订单动态可以点击上一页，下一页；
     *     参数2：总数量；
     *     参数3：当前页数，每页暂时固定4列；
     */
    fun updatePageBtn(visible: Boolean) {
        if (visible) {
            binding.tvNextPage.alpha = 1f
            binding.tvNextPage.isEnabled = true
            binding.tvPreviousPagev.alpha = 1f
            binding.tvPreviousPagev.isEnabled = true
        } else {
            binding.tvNextPage.alpha = 0.5f
            binding.tvNextPage.isEnabled = false
            binding.tvPreviousPagev.alpha = 0.5f
            binding.tvPreviousPagev.isEnabled = false
        }
    }
}